package com.wx.mall.operate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.mall.operate.entity.RebSort;
import com.wx.mall.operate.entity.VSort;
import com.wx.mall.operate.mapper.VSortMapper;
import com.wx.mall.operate.service.IRebSortService;
import com.wx.mall.operate.service.IVSortService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.mall.operate.vo.RebSortReqNodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author j
 * @since 2020-06-09
 */
@Service
public class VSortServiceImpl extends ServiceImpl<VSortMapper, VSort> implements IVSortService {

    @Autowired
    IVSortService ivSortService;

    @Autowired
    IRebSortService iRebSortService;

    @Override
    public List<RebSortReqNodeVo> findSortList(Long ids) {
        QueryWrapper<VSort> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("rebate_id",ids);
        List<VSort> list1 = this.list(queryWrapper);
        List<RebSortReqNodeVo> tree=findTree(list1);
        return tree;
    }

    private List<RebSortReqNodeVo> findTree(List<VSort> all){
        List<RebSortReqNodeVo> reqNodeVos = JSON.parseArray(JSON.toJSONString(all), RebSortReqNodeVo.class);
        List<RebSortReqNodeVo> list1=new ArrayList<>();
        if (all.isEmpty()){
            return list1;
        }
        for (RebSortReqNodeVo rebSort:reqNodeVos
        ) {
            if (rebSort.getTotalId()==0){
                rebSort.setChildren(findChildren(rebSort.getId(),all));
                list1.add(rebSort);
            }
        }
        return list1;
    }

    private List<RebSortReqNodeVo> findChildren(Long id,List<VSort> all){
        List<RebSortReqNodeVo> reqNodeVos = JSON.parseArray(JSON.toJSONString(all), RebSortReqNodeVo.class);
        List<RebSortReqNodeVo> list=new ArrayList<>();
        for (RebSortReqNodeVo reb:reqNodeVos
        ) {
            if (reb.getTotalId()==id){
                list.add(reb);
            }
        }
        return list;
    }

    @Override
    public List<Long> getVSort(Long ids) {
        QueryWrapper<VSort> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("rebate_id",ids);
        List<VSort> list=this.list(queryWrapper);
        List<Long> list1=new ArrayList<>();
        for (VSort vsort:list
             ) {
            queryWrapper.eq("id",vsort.getId());
            RebSort byId = iRebSortService.getById(vsort.getId());
            if (byId.getType()==2){
                list1.add(byId.getId());
            }
        }
        return list1;
    }

}
